<template>
  <div class="table-box">
    <!-- 搜索表单 -->
    <el-form :model="searchForm" ref="searchFormRef" :inline="true" class="search-form">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="searchForm.roleName" placeholder="请输入角色名称" clearable />
      </el-form-item>
      <el-form-item label="角色编码" prop="roleCode">
        <el-input v-model="searchForm.roleCode" placeholder="请输入角色编码" clearable />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 180px">
          <el-option label="启用" value="ACTIVE" />
          <el-option label="禁用" value="INACTIVE" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="table-header">
      <el-button type="primary" :icon="CirclePlus" @click="handleAdd">新增角色</el-button>
      <el-button type="success" :icon="Download" @click="handleExport">导出</el-button>
    </div>

    <el-table :data="tableData" style="width: 100%" v-loading="loading" border>
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="roleCode" label="角色编码" />
      <el-table-column prop="roleName" label="角色名称" />
      <el-table-column prop="description" label="角色描述" show-overflow-tooltip />
      <el-table-column prop="permissions" label="权限数量" align="center">
        <template #default="scope">
          <el-tag type="info">{{ scope.row.permissions?.length || 0 }}个权限</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="userCount" label="用户数量" align="center">
        <template #default="scope">
          <el-tag type="primary">{{ scope.row.userCount }}个用户</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" align="center">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column prop="updateTime" label="更新时间" />
      <el-table-column label="操作" width="280" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="handleView(scope.row)">查看</el-button>
          <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="warning" link @click="handlePermission(scope.row)">权限配置</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>

    <!-- 新增/编辑角色对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="roleForm" :rules="roleRules" ref="roleFormRef" label-width="100px">
        <el-form-item label="角色编码" prop="roleCode">
          <el-input v-model="roleForm.roleCode" placeholder="请输入角色编码" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="roleForm.status">
            <el-radio value="ACTIVE">启用</el-radio>
            <el-radio value="INACTIVE">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限配置对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="权限配置"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="permission-container">
        <div class="permission-header">
          <span>为角色 "{{ currentRole?.roleName }}" 配置权限</span>
        </div>
        <el-tree
          ref="permissionTreeRef"
          :data="permissionTreeData"
          show-checkbox
          node-key="id"
          :default-expanded-keys="expandedKeys"
          :default-checked-keys="checkedKeys"
          :props="treeProps"
          class="permission-tree"
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSavePermission">保存权限</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="roleManage">
import { ref, reactive, onMounted } from "vue";
import type { FormInstance } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { CirclePlus, Download } from "@element-plus/icons-vue";

// 定义数据类型
interface RoleData {
  id: string;
  roleCode: string;
  roleName: string;
  description: string;
  permissions: string[];
  userCount: number;
  status: string;
  createTime: string;
  updateTime: string;
}

interface PermissionNode {
  id: string;
  label: string;
  children?: PermissionNode[];
}

const loading = ref(false);
const tableData = ref<RoleData[]>([]);
const searchFormRef = ref<FormInstance>();
const roleFormRef = ref<FormInstance>();
const permissionTreeRef = ref();

// 对话框相关
const dialogVisible = ref(false);
const permissionDialogVisible = ref(false);
const dialogTitle = ref("");
const isEdit = ref(false);
const currentRole = ref<RoleData | null>(null);

// 查询表单
const searchForm = reactive({
  roleName: "",
  roleCode: "",
  status: ""
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 角色表单
const roleForm = reactive({
  id: "",
  roleCode: "",
  roleName: "",
  description: "",
  status: "ACTIVE"
});

// 表单验证规则
const roleRules = {
  roleCode: [
    { required: true, message: "请输入角色编码", trigger: "blur" },
    { min: 2, max: 20, message: "角色编码长度在 2 到 20 个字符", trigger: "blur" }
  ],
  roleName: [
    { required: true, message: "请输入角色名称", trigger: "blur" },
    { min: 2, max: 50, message: "角色名称长度在 2 到 50 个字符", trigger: "blur" }
  ],
  status: [
    { required: true, message: "请选择状态", trigger: "change" }
  ]
};

// 权限树相关
const permissionTreeData = ref<PermissionNode[]>([]);
const expandedKeys = ref<string[]>([]);
const checkedKeys = ref<string[]>([]);
const treeProps = {
  children: 'children',
  label: 'label'
};
// 获取状态类型
const getStatusType = (status: string) => {
  return status === "ACTIVE" ? "success" : "danger";
};

// 获取状态文本
const getStatusText = (status: string) => {
  return status === "ACTIVE" ? "启用" : "禁用";
};

// 获取表格数据
const getTableData = async () => {
  loading.value = true;
  try {
    // 模拟数据
    const mockData: RoleData[] = [
      {
        id: "1",
        roleCode: "ADMIN",
        roleName: "系统管理员",
        description: "拥有系统所有权限，可以管理用户、角色、权限等",
        permissions: ["user:view", "user:add", "user:edit", "user:delete", "role:view", "role:add", "role:edit", "role:delete"],
        userCount: 2,
        status: "ACTIVE",
        createTime: "2024-01-01 10:00:00",
        updateTime: "2024-01-15 14:30:00"
      },
      {
        id: "2",
        roleCode: "PRODUCTION_MANAGER",
        roleName: "生产经理",
        description: "负责生产管理相关功能，包括生产计划、工单管理等",
        permissions: ["production:view", "production:add", "production:edit", "workorder:view", "workorder:add"],
        userCount: 5,
        status: "ACTIVE",
        createTime: "2024-01-02 09:00:00",
        updateTime: "2024-01-10 16:20:00"
      },
      {
        id: "3",
        roleCode: "QUALITY_INSPECTOR",
        roleName: "质量检验员",
        description: "负责质量检验相关功能，包括检验标准、检验记录等",
        permissions: ["quality:view", "inspection:view", "inspection:add", "inspection:edit"],
        userCount: 8,
        status: "ACTIVE",
        createTime: "2024-01-03 08:30:00",
        updateTime: "2024-01-12 11:45:00"
      },
      {
        id: "4",
        roleCode: "WAREHOUSE_KEEPER",
        roleName: "仓库管理员",
        description: "负责库存管理相关功能，包括入库、出库、盘点等",
        permissions: ["inventory:view", "inventory:add", "inventory:edit", "warehouse:view"],
        userCount: 3,
        status: "ACTIVE",
        createTime: "2024-01-04 07:45:00",
        updateTime: "2024-01-08 13:15:00"
      },
      {
        id: "5",
        roleCode: "OPERATOR",
        roleName: "操作员",
        description: "基础操作权限，只能查看相关数据",
        permissions: ["dashboard:view", "production:view", "quality:view"],
        userCount: 15,
        status: "ACTIVE",
        createTime: "2024-01-05 09:15:00",
        updateTime: "2024-01-14 10:30:00"
      },
      {
        id: "6",
        roleCode: "GUEST",
        roleName: "访客",
        description: "临时访客角色，权限受限",
        permissions: ["dashboard:view"],
        userCount: 0,
        status: "INACTIVE",
        createTime: "2024-01-06 14:20:00",
        updateTime: "2024-01-06 14:20:00"
      }
    ];
    
    tableData.value = mockData;
    pagination.total = mockData.length;
  } catch (error) {
    console.error("获取角色数据失败:", error);
    ElMessage.error("获取角色数据失败");
  } finally {
    loading.value = false;
  }
};

// 初始化权限树数据
const initPermissionTree = () => {
  permissionTreeData.value = [
    {
      id: "system",
      label: "系统管理",
      children: [
        { id: "user:view", label: "用户查看" },
        { id: "user:add", label: "用户新增" },
        { id: "user:edit", label: "用户编辑" },
        { id: "user:delete", label: "用户删除" },
        { id: "role:view", label: "角色查看" },
        { id: "role:add", label: "角色新增" },
        { id: "role:edit", label: "角色编辑" },
        { id: "role:delete", label: "角色删除" }
      ]
    },
    {
      id: "production",
      label: "生产管理",
      children: [
        { id: "production:view", label: "生产查看" },
        { id: "production:add", label: "生产新增" },
        { id: "production:edit", label: "生产编辑" },
        { id: "workorder:view", label: "工单查看" },
        { id: "workorder:add", label: "工单新增" },
        { id: "workorder:edit", label: "工单编辑" }
      ]
    },
    {
      id: "quality",
      label: "质量管理",
      children: [
        { id: "quality:view", label: "质量查看" },
        { id: "inspection:view", label: "检验查看" },
        { id: "inspection:add", label: "检验新增" },
        { id: "inspection:edit", label: "检验编辑" },
        { id: "standard:view", label: "标准查看" },
        { id: "standard:add", label: "标准新增" }
      ]
    },
    {
      id: "inventory",
      label: "库存管理",
      children: [
        { id: "inventory:view", label: "库存查看" },
        { id: "inventory:add", label: "库存新增" },
        { id: "inventory:edit", label: "库存编辑" },
        { id: "warehouse:view", label: "仓库查看" },
        { id: "warehouse:add", label: "仓库新增" }
      ]
    },
    {
      id: "report",
      label: "报表管理",
      children: [
        { id: "report:production", label: "生产报表" },
        { id: "report:quality", label: "质量报表" },
        { id: "report:inventory", label: "库存报表" },
        { id: "report:equipment", label: "设备报表" }
      ]
    },
    {
      id: "dashboard",
      label: "仪表盘",
      children: [
        { id: "dashboard:view", label: "仪表盘查看" }
      ]
    }
  ];
  
  // 默认展开所有节点
  expandedKeys.value = ["system", "production", "quality", "inventory", "report", "dashboard"];
};

// 查询
const handleSearch = () => {
  pagination.currentPage = 1;
  getTableData();
};

// 重置
const handleReset = () => {
  if (!searchFormRef.value) return;
  searchFormRef.value.resetFields();
  pagination.currentPage = 1;
  getTableData();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  getTableData();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  getTableData();
};

// 新增角色
const handleAdd = () => {
  dialogTitle.value = "新增角色";
  isEdit.value = false;
  Object.assign(roleForm, {
    id: "",
    roleCode: "",
    roleName: "",
    description: "",
    status: "ACTIVE"
  });
  dialogVisible.value = true;
};

// 查看角色
const handleView = (row: RoleData) => {
  ElMessage.info(`查看角色: ${row.roleName}`);
};

// 编辑角色
const handleEdit = (row: RoleData) => {
  dialogTitle.value = "编辑角色";
  isEdit.value = true;
  Object.assign(roleForm, { ...row });
  dialogVisible.value = true;
};

// 权限配置
const handlePermission = (row: RoleData) => {
  currentRole.value = row;
  checkedKeys.value = row.permissions || [];
  permissionDialogVisible.value = true;
};

// 删除角色
const handleDelete = async (row: RoleData) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${row.roleName}" 吗？`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );
    
    ElMessage.success("删除成功");
    getTableData();
  } catch {
    ElMessage.info("已取消删除");
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!roleFormRef.value) return;
  
  try {
    await roleFormRef.value.validate();
    
    // 这里应该调用API保存数据
    ElMessage.success(isEdit.value ? "编辑成功" : "新增成功");
    dialogVisible.value = false;
    getTableData();
  } catch (error) {
    console.error("表单验证失败:", error);
  }
};

// 保存权限配置
const handleSavePermission = () => {
  if (!permissionTreeRef.value || !currentRole.value) return;
  
  const checkedNodes = permissionTreeRef.value.getCheckedKeys();
  const halfCheckedNodes = permissionTreeRef.value.getHalfCheckedKeys();
  const allCheckedKeys = [...checkedNodes, ...halfCheckedNodes];
  
  // 这里应该调用API保存权限配置
  ElMessage.success("权限配置保存成功");
  permissionDialogVisible.value = false;
  getTableData();
};

// 导出
const handleExport = () => {
  ElMessage.info("导出角色数据功能开发中");
};

// 页面加载时获取数据
onMounted(() => {
  getTableData();
  initPermissionTree();
});
</script>

<style scoped>
.table-box {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.permission-container {
  max-height: 400px;
  overflow-y: auto;
}

.permission-header {
  margin-bottom: 15px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  font-weight: bold;
}

.permission-tree {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>